package com.cby.jetpack.sample.binding.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.cby.jetpack.sample.R
import com.cby.jetpack.sample.binding.data.Example
import com.cby.jetpack.sample.databinding.ItemDataBinding
import com.cby.jetpack.sample.ext.showToast

/**
 * @description: TestListAdapter
 *
 * @author ChenBaoyang
 * @date 8/9/21 18:01
 */
class TestListAdapter : RecyclerView.Adapter<TestListAdapter.TestListViewHolder>() {


    private val dataList: MutableList<Example> = mutableListOf()

    class TestListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var binding: ItemDataBinding? = DataBindingUtil.bind(itemView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TestListViewHolder {
        return TestListViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_data, parent, false))
    }

    override fun onBindViewHolder(holder: TestListViewHolder, position: Int) {
        holder.binding?.example = dataList[position]
        holder.itemView.setOnClickListener {
            it.context.showToast(dataList[position].text)
        }
    }

    override fun getItemCount() = dataList.size

    /**
     * 添加列表数据
     *
     * @param dataList MutableList<Example>
     */
    fun addData(dataList: MutableList<Example>) {
        this.dataList.clear()
        this.dataList.addAll(dataList)
        notifyDataSetChanged()
    }
}